<template>
  <div class="opBar">
<!--      期刊名称-->
      <div class="paperSrc">{{paperSource}}</div>


      <div>
        <el-button @click="quoteGenerate" type="primary"  icon="el-icon-link" circle></el-button>
<!--        进行收藏-->
        <el-button v-show="!isPaperCollected" @click="addToLib" type="primary" size="" icon="el-icon-star-off" circle></el-button>
<!--        取消收藏-->
        <el-button v-show="isPaperCollected" @click="deleteFromLib" icon="el-icon-star-off" circle></el-button>

      </div>


  </div>


<!--收藏夹弹窗-->
  <el-dialog v-model="dialogFormVisible" title="收藏夹">

    <!--    中央内容-->
    <div class="selectContent">
      <el-select v-model="selectedFolder"
                 filterable placeholder="筛选或新建收藏夹"
                 @change="testSelect"
                 allow-create>
        <el-option
            v-for="folder in collectFolders"
            :key="folder.folderId"
            :label="folder.folderName"
            :value="folder.folderId"
        >
          {{folder.folderName}}
        </el-option>
      </el-select>

      <span>文章数量：{{collectionNum}}</span>
    </div>


<!--    操作按钮-->
    <div class="collectionBtn">
      <el-button @click="closeCollectionDialog" size="small">取消</el-button>
      <el-button @click="confirmCollect" size="small" type="primary">确定</el-button>
    </div>

  </el-dialog>


<!--  引用框弹窗-->
  <el-dialog v-model="quoteVisible" title="引用">
    <div>
      <el-card class="box-card">
        <div id="quote">
          {{quoteContent}}
          <el-button @click="copyQuote" class="copyBtn" size="mini">复制</el-button>
        </div>
      </el-card>
    </div>
  </el-dialog>


</template>

<script>



import axios from "@/utils/MyAxios";
import qs from "qs";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  name: "DetailOpBar",
  props: ['paper'],
  data() {
    return {
      activeName: 'first',
      dialogFormVisible:false,
      quoteVisible:false,

      isPaperCollected: false,

      // 收藏弹窗 绑定选择值
      selectedFolder: ref(''),

      // 收藏弹窗 此用户的所有收藏夹
      collectFolders: [
        {
          folderId: 1,
          folderName: 'c1',
          count: 0,
        },
        {
          folderId: 2,
          folderName: 'c2',
          count: 1,
        }
      ],

      addFolder: -1,
      currCollectionFolderId: -1,
    }
  },
  computed: {
    collectionNum() {
      let index = 0
      for (;index < this.collectFolders.length;) {
        let folder = this.collectFolders[index]
        if (folder.folderId === this.selectedFolder) {
          return folder.count
        }
        index = index + 1
      }

      return 0
    },

    paperSource() {
      // 期刊
      if (this.paper.journal !== null) {
        let date = ''+this.paper.date
        return this.paper.journal+'.'+date.substr(0,4)
      }
      // 会议
      else if (this.paper.conferenceSeries !== null) {
        let interact = this.paper.conferenceInstance
        return this.paper.conferenceSeries +', '+interact
      }
      else {
        return '暂无文献来源'
      }

    },

    quoteContent() {
      let quote = ''
      quote = quote + '[1]'
      // 添加作者
      for (let index=0; index < this.paper.authors.length; index++) {
        let item = this.paper.authors.at(index)
        quote += item.author+','
      }
      // 去掉逗号，添加句号和标题
      if (this.paper.authors.length > 0) {
        quote = quote.substring(0, quote.length - 1) + '.' + this.paper.title
      }
      else {
        quote += this.paper.title
      }

      // 添加来源
      if (this.paper.journal !== null) {
        quote += '[J].'+this.paper.journal+','+this.paper.year
        if (this.paper.firstPage !== "") {
          console.log(this.paper.firstPage)
          quote += ':'+this.paper.firstPage+'-'+this.paper.lastPage
        }
        quote += '.'
      }
      else if (this.paper.conferenceSeries !== null) {
        quote += '[C]//'+this.paper.conferenceSeries+'.[出版者不详],'+this.paper.year
        if (this.paper.firstPage !== "") {
          console.log(this.paper.firstPage)
          quote += ':'+this.paper.firstPage+'-'+this.paper.lastPage
        }
        quote += '.'

      }
      return quote
    },
  },
  methods: {
    quoteGenerate() {
      this.quoteVisible = true
    },

    copyQuote() {
      const node = document.getElementById('quote')
      if (node) {
        let createRange = document.createRange()
        createRange.selectNodeContents(document.getElementById('quote'))
        const selection = document.getSelection()
        selection.removeAllRanges()
        selection.addRange(createRange)
        document.execCommand('Copy')
        selection.removeAllRanges()
        ElMessage({
          message: '复制成功',
          type: 'success',
        })      }
    },

    // 添加收藏
    addToLib() {
      console.log("lib")

      let isLogin = JSON.parse(localStorage.getItem('user')) !== null
      // let isLogin = true

      // 未登录状态
      if (!isLogin) {
        ElMessage({
          message: '请先进行登录',
          type: 'warning',
        })
      }
      // 已经登录
      else {
        this.selectedFolder = ref('') // 清空选择
        this.dialogFormVisible = true //TODO:删除这一行
        //TODO: 在生成引用格式的地方，对空信息debug
        let data = {
          token: JSON.parse(localStorage.getItem('user')).token
        }
        axios.post('/api/folder/list', qs.stringify(data)).then(res => {
          console.log(res);
          if (res.data.code === 0) {
            this.collectFolders = res.data.data
            this.dialogFormVisible = true

          }
          else {
            console.log("获取收藏夹列表错误")
          }
        })

      }
    },


    testSelect() {
      console.log("1234")
      console.log('select' + this.selectedFolder);
    },


    // 收藏文献
    addCollection(folderId) {
      console.log('收藏文献func')

      let token = JSON.parse(localStorage.getItem('user')).token
      console.log(folderId);
      let data = {
        token: token,
        paperId: this.$route.query.paperId,
        folderId: folderId
      }
      console.log('data'+ data)

      if (data.folderId === null) {
        console.log("文件夹添加信息ERR")
      }

      axios.post('/api/collection/add', qs.stringify(data)).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.isPaperCollected = true
          ElMessage({
            type: 'success',
            message: '收藏成功',
          })
          this.dialogFormVisible = false
        }
        else if (res.data.code === 1) {
          this.isPaperCollected = false
          ElMessage({
            type: 'warning',
            message: '您已经收藏此文献',
          })
        }
        else if (res.data.code === 2) {
          ElMessage({
            type: 'warning',
            message: '此收藏夹已满',
          })
        }
      })

    },


    // 判断是否被收藏
    isCollected() {
      let isLogin = (JSON.parse(localStorage.getItem('user'))) != null

      if (!isLogin)
        return

      let userToken = ''+JSON.parse(localStorage.getItem('user')).token
      console.log('usertoken'+userToken)
      let data = {
        token: userToken,
        paperId: this.$route.query.paperId,
      }
      axios.post('/api/collection/check', qs.stringify(data)).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.isPaperCollected = false
        }
        else if (res.data.code === 1) {
          this.isPaperCollected = true
        }
      })
    },


    // 进行收藏 点击确认按钮
    confirmCollect() {
      let theFolder =  null

      let theToken = JSON.parse(localStorage.getItem('user')).token

      for (let index = 0; index < this.collectFolders.length; index++) {
        if (this.collectFolders[index].folderId === this.selectedFolder) {
          theFolder = this.collectFolders[index].folderId
          break
        }
      }

      console.log('theFolder'+theFolder)

      // 不是新建文件夹
      if (theFolder !== null) {
        console.log('not new folder')
        console.log(theFolder)
        this.addCollection(theFolder)
      }
      // 是新建文件夹
      else {
        console.log(' new folder')

        let data = {
          token: theToken,
          folderName: this.selectedFolder
        }
        axios.post('/api/folder/add', qs.stringify(data)).then(res => {
          console.log(res);
          if (res.data.code === 0) {
            this.addCollection(res.data.data.folderId)
          }
          else if (res.data.code === 1) {
            console.log('收藏夹重名')
          }
          else if (res.data.code === 2) {
            console.log('收藏夹数量达到上限')
          }
        })
      }

    },


    // 取消收藏
    deleteFromLib() {
      ElMessageBox.confirm(
          '您是否要取消收藏此文章',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(() => {
            console.log('取消收藏');

            let token = JSON.parse(localStorage.getItem('user')).token
            let data = {
              token: token,
              paperId: this.$route.query.paperId,
            }
            axios.post('/api/collection/cancel', qs.stringify(data)).then(res => {
              console.log(res);
              if (res.data.code === 0) {
                this.isPaperCollected = false
                ElMessage({
                  type: 'success',
                  message: '成功取消收藏',
                })
              }
              else if (res.data.code === 1) {
                console.log('没有此文献收藏')
              }
            })

          })
          .catch(() => {

          })
    },


    // 关闭收藏弹窗
    closeCollectionDialog() {
      this.dialogFormVisible = false
    },


    checkIsPaperCollected() {
      console.log('查看文献是否被收藏');
      let token = JSON.parse(localStorage.getItem('user'))

      if (token === null) return
      else token = token.token

      let data = {
        token: token,
        paperId: this.$route.query.paperId,
      }
      axios.post('/api/collection/check', qs.stringify(data)).then(res => {
        console.log(res);
        if (res.data.code === 0) {
          this.isPaperCollected = false
        }
        else if (res.data.code === 1) {
          console.log('文献已经收藏');
          this.isPaperCollected = true
        }
        else {
          console.log('收藏判断失败ERR');
        }
      })
    },
  },
  mounted() {
    this.checkIsPaperCollected()
  }
}
</script>

<style scoped>

  .paperSrc {


    font-size: medium;
  }

  .selectContent {
    display: flex;
    justify-content: space-between;
    align-items: baseline;
  }

  .collectionBtn {
    display: flex;
    justify-content: center;

    margin-top: 2%;
  }

  .opBar {
    margin-top: 50px;
    margin-left: 10%;
    margin-right: 10%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }


  .copyBtn {
    margin-top: 10px;
  }
</style>